package com.post799.soundapp;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONArray;
import org.json.JSONObject;

import kankan.wheel.widget.WheelView;
import kankan.wheel.widget.adapters.AbstractWheelTextAdapter;
import kankan.wheel.widget.adapters.NumericWheelAdapter;

import com.bappi.custom.activities.CustomActivity;
import com.bappi.utils.Constants;
import com.bappi.utils.Utils;
import com.whitenoise.model.Alarm;
import com.whitenoise.model.CalendarHelper;
import com.whitenoise.model.CustomCalendar;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.pm.ActivityInfo;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class Tab3Activity1 extends CustomActivity {

	private WheelView mDay, mHours, mMins;
	private SharedPreferences sp;
	private OnSharedPreferenceChangeListener ospcl;
	private ListView listView;
	private List<Alarm> alarms;
	private AlarmAdapter alarmAdapter;

	private CheckBox snoozeCheckBox;

	private int selectedAlarmId = 0;
	private String selectedAlarmFileName;
	private String selectedAlarmTitle;
	private long alarmTime;
	private Handler mHandler;

	private RelativeLayout messageContainer;
	private TextView messageView;
	private Button setOrCancelAlarm;
	private Button listenOrStopButton;
	
	private MediaPlayer mAlarmMediaPlayer;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		try {
			super.onCreate(savedInstanceState);
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
			setContentView(R.layout.layout_tab_3_screen_1);
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
			mHandler = new Handler();
			sp = PreferenceManager.getDefaultSharedPreferences(getParent());
			ospcl = new OnSharedPreferenceChangeListener() {

				public void onSharedPreferenceChanged(
						final SharedPreferences sp, String key) {
					try {
						
						if (Constants.KEY_ALARM_TIME.equals(key)) {
							runOnUiThread(new Runnable() {
								@Override
								public void run() {
									try {
										alarmTime = sp.getLong(Constants.KEY_ALARM_TIME, 0);
										if (alarmTime > System.currentTimeMillis()) {
											setOrCancelAlarm
													.setText(getString(R.string.cancel_alarm));
											startTimer();
										} else {
											setOrCancelAlarm
													.setText(getString(R.string.set_alarm));
										}
									} catch (Exception e) {
										e.printStackTrace();
									}
								}
							});
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			};
			sp.registerOnSharedPreferenceChangeListener(ospcl);
			
			listView = (ListView) this.findViewById(R.id.list_view);
			alarms = new ArrayList<Alarm>();

			selectedAlarmId = sp.getInt(Constants.KEY_ALARM_ID, -1);
			selectedAlarmFileName = sp
					.getString(Constants.KEY_ALARM_FILE, null);
			selectedAlarmTitle = sp.getString(Constants.KEY_ALARM_TITLE, null);
			alarmTime = sp.getLong(Constants.KEY_ALARM_TIME, 0);

			messageContainer = (RelativeLayout) findViewById(R.id.message_container);
			messageView = (TextView) findViewById(R.id.message_view);
			snoozeCheckBox = (CheckBox) findViewById(R.id.isSnoozeAble);
			snoozeCheckBox.setChecked(sp.getBoolean(
					Constants.KEY_ALARM_ENABLE_SNOOZE, false));
			snoozeCheckBox
					.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
						@Override
						public void onCheckedChanged(CompoundButton arg0,
								boolean isChecked) {
							sp.edit()
									.putBoolean(
											Constants.KEY_ALARM_ENABLE_SNOOZE,
											isChecked).commit();
						}
					});
			setOrCancelAlarm = (Button) findViewById(R.id.setAlarmBtn);
			setOrCancelAlarm.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					startOrStopAlarm();
				}
			});
			listenOrStopButton = (Button) findViewById(R.id.listenBtn);
			listenOrStopButton.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					listenOrStop();
				}
			});

			mHours = (WheelView) findViewById(R.id.hour);
			NumericWheelAdapter hourAdapter = new NumericWheelAdapter(
					getParent(), 0, 23, "%02d");
			hourAdapter.setItemResource(R.layout.wheel_text_item);
			hourAdapter.setItemTextResource(R.id.text);
			mHours.setViewAdapter(hourAdapter);

			mMins = (WheelView) findViewById(R.id.mins);
			NumericWheelAdapter minAdapter = new NumericWheelAdapter(
					getParent(), 0, 59, "%02d");
			minAdapter.setItemResource(R.layout.wheel_text_item);
			minAdapter.setItemTextResource(R.id.text);
			mMins.setViewAdapter(minAdapter);
			mMins.setCyclic(true);

			// set current time
			Calendar calendar = Calendar.getInstance(Locale.US);
			calendar.setTimeInMillis(System.currentTimeMillis());

			mDay = (WheelView) findViewById(R.id.day);
			mDay.setViewAdapter(new DayArrayAdapter(getParent(), calendar));
			mDay.setCyclic(true);
			mDay.setCurrentItem(182);

			// mDay.setCurrentItem(calendar.get(Calendar.DAY_OF_YEAR));
			mHours.setCurrentItem(calendar.get(Calendar.HOUR_OF_DAY));
			mMins.setCurrentItem(calendar.get(Calendar.MINUTE));

			new AsyncTask<String, String, String>() {
				private ProgressDialog progressDialog;
				private int selectedIndex = 0;

				protected void onPreExecute() {
					try {
						progressDialog = Utils.getProgressDialog(getParent());
						progressDialog.show();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				protected String doInBackground(String... arg0) {
					try {
						JSONArray ja = Utils.getAlarmInfo(getParent());
						JSONObject jo;
						Alarm alarm;
						int id;
						for (int i = 0; i < ja.length(); i++) {
							jo = ja.getJSONObject(i);
							alarm = new Alarm();
							id = jo.getInt("ID");
							alarm.setTitle(jo.getString("title"));
							alarm.setFileName(jo.getString("audioFile"));
							alarm.setId(id);
							if(id == selectedAlarmId){
								selectedIndex = i;
							}
							alarms.add(alarm);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
					return null;
				}

				protected void onPostExecute(String unused) {
					try {
						alarmAdapter = new AlarmAdapter(getParent());
						listView.setAdapter(alarmAdapter);
						listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

							@Override
							public void onItemClick(AdapterView<?> av, View v,
									int position, long arg) {
								selectedAlarmId = ((Alarm) alarmAdapter
										.getItem(position)).getId();
								selectedAlarmFileName = ((Alarm) alarmAdapter
										.getItem(position)).getFileName();
								selectedAlarmTitle = ((Alarm) alarmAdapter
										.getItem(position)).getTitle();
								sp.edit()
										.putInt(Constants.KEY_ALARM_ID,
												selectedAlarmId).commit();
								sp.edit()
										.putString(Constants.KEY_ALARM_FILE,
												selectedAlarmFileName).commit();
								sp.edit()
										.putString(Constants.KEY_ALARM_TITLE,
												selectedAlarmTitle).commit();
								alarmAdapter.notifyDataSetChanged();
								
								if (getString(R.string.stop).equals(
										listenOrStopButton.getText().toString())) {
									if(selectedAlarmFileName!=null){
										if(mAlarmMediaPlayer!=null){
											mAlarmMediaPlayer.stop();
										}
										mAlarmMediaPlayer =MediaPlayer.create(getParent(),Utils.getResourceID(selectedAlarmFileName, "raw",getParent()));
										mAlarmMediaPlayer.start();
										mAlarmMediaPlayer.setLooping(true);;
									}
								}	
							}
						});
						listView.setSelection(selectedIndex);
						progressDialog.dismiss();
						listenOrStopButton
						.setText(getString(R.string.listen));
						if (alarmTime > System.currentTimeMillis()) {
							setOrCancelAlarm
									.setText(getString(R.string.cancel_alarm));
							startTimer();
						} else {
							setOrCancelAlarm
									.setText(getString(R.string.set_alarm));
						}

					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}.execute();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	@Override
	protected void onDestroy() {
		try {
			if(mAlarmMediaPlayer!=null){
				mAlarmMediaPlayer.stop();
				if (sp != null && ospcl != null) {
					sp.unregisterOnSharedPreferenceChangeListener(ospcl);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		super.onDestroy();
	}

	/**
	 * Day adapter
	 * 
	 */
	private class DayArrayAdapter extends AbstractWheelTextAdapter {
		// Count of days to be shown
		private final int daysCount = 365;

		// Calendar
		Calendar calendar;

		/**
		 * Constructor
		 */
		protected DayArrayAdapter(Context context, Calendar calendar) {
			super(context, R.layout.alarm2_day, NO_RESOURCE);
			this.calendar = calendar;

			setItemTextResource(R.id.time2_monthday);
		}

		@Override
		public View getItem(int index, View cachedView, ViewGroup parent) {
			int day = -daysCount / 2 + index;
			Calendar newCalendar = (Calendar) calendar.clone();
			newCalendar.roll(Calendar.DAY_OF_YEAR, day);

			View view = super.getItem(index, cachedView, parent);
			TextView weekday = (TextView) view.findViewById(R.id.time2_weekday);
			if (day == 0) {
				weekday.setText("");
			} else {
				DateFormat format = new SimpleDateFormat("EEE");
				weekday.setText(format.format(newCalendar.getTime()));
			}

			TextView monthday = (TextView) view
					.findViewById(R.id.time2_monthday);
			if (day == 0) {
				monthday.setText("Today");
				monthday.setTextColor(0xFF0000F0);
			} else {
				DateFormat format = new SimpleDateFormat("MMM d");
				monthday.setText(format.format(newCalendar.getTime()));
				monthday.setTextColor(0xFF111111);
			}

			return view;
		}

		@Override
		public int getItemsCount() {
			return daysCount + 1;
		}

		@Override
		protected CharSequence getItemText(int index) {
			return "";
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		try {
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void startOrStopAlarm(){
		try {
			if (getString(R.string.cancel_alarm).equals(
					setOrCancelAlarm.getText().toString())) {
				Intent intent = new Intent(getParent(),
						AlarmReciverActivity.class);
				PendingIntent pendingIntent = PendingIntent.getActivity(
						getParent(), 12345, intent, 0);
				AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
				alarmManager.cancel(pendingIntent);

				alarmTime = 0;
				sp.edit().putLong(Constants.KEY_ALARM_TIME, alarmTime)
						.commit();
			} else {
				if (selectedAlarmId >= 0) {
					Calendar calendar = Calendar.getInstance();
					int hours = calendar.getTime().getHours();
					int minuties = calendar.getTime().getMinutes();
					int days = calendar.getTime().getDay();

					Date currentDate = new Date(System.currentTimeMillis());
					Log.d("DEBUG", currentDate.getMinutes() + " "
							+ currentDate.getDate());
					days = mDay.getCurrentItem() - days;
					Log.d("DEBUG", days + "");
					hours = mHours.getCurrentItem() - hours;
					minuties = mMins.getCurrentItem() - minuties;

					CalendarHelper ob = new CalendarHelper();
					CustomCalendar ob1 = ob.getMyCal(mDay.getCurrentItem());
					Log.d("DEBUG", ob1.date + " " + ob1.month);

					int miliSeconds = (((hours * 60 * 60) + (minuties * 60)) * 1000);

					if (miliSeconds >= 0) {
						Intent intent = new Intent(getParent(),
								AlarmReciverActivity.class);
						PendingIntent pendingIntent = PendingIntent
								.getActivity(getParent(), 12345, intent,
										PendingIntent.FLAG_CANCEL_CURRENT);
						alarmTime = (System.currentTimeMillis() + miliSeconds);
						AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
						am.set(AlarmManager.RTC_WAKEUP, alarmTime,
								pendingIntent);
						sp.edit()
								.putLong(Constants.KEY_ALARM_TIME,
										alarmTime).commit();
						setOrCancelAlarm.setText(getString(R.string.cancel_alarm));
						Utils.showAlertMessage(
								getParent(),
								getString(R.string.message_alarm_set_successfully));
					} else {
						Utils.showAlertMessage(
								getParent(),
								getString(R.string.message_select_alarm_time));
					}
				} else {
					Utils.showAlertMessage(getParent(),
							getString(R.string.message_select_alarm_tone));
				}	
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	private void listenOrStop(){
		try {
			if (getString(R.string.listen).equals(
					listenOrStopButton.getText().toString())) {
				if(selectedAlarmFileName!=null){	
					if(mAlarmMediaPlayer!=null){
						mAlarmMediaPlayer.stop();
					}
					mAlarmMediaPlayer =MediaPlayer.create(this,Utils.getResourceID(selectedAlarmFileName, "raw",getParent()));
					mAlarmMediaPlayer.start();
					mAlarmMediaPlayer.setLooping(true);
					listenOrStopButton.setText(getString(R.string.stop));
				}else {
					Utils.showAlertMessage(getParent(),
							getString(R.string.message_select_alarm_tone));
				}
			}else{
				mAlarmMediaPlayer.stop();
				listenOrStopButton.setText(getString(R.string.listen));
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
	}


	public class AlarmAdapter extends BaseAdapter {
		private LayoutInflater mInflater;
		private Context context;

		public AlarmAdapter(Context context) {
			mInflater = LayoutInflater.from(context);
			this.context = context;
		}

		public View getView(final int position, View convertView,
				ViewGroup parent) {
			try {
				ViewHolder holder;
				if (convertView == null) {
					convertView = mInflater.inflate(R.layout.alarm_item, null);
					holder = new ViewHolder();
					holder.mainContainer = convertView
							.findViewById(R.id.main_container);
					holder.titleView = (TextView) convertView
							.findViewById(R.id.text_view);
					holder.imageView = (ImageView) convertView
							.findViewById(R.id.tick_image_view);
					convertView.setTag(holder);
				} else {
					holder = (ViewHolder) convertView.getTag();
				}
				if (alarms.get(position).getId() == selectedAlarmId) {
					holder.imageView.setVisibility(View.VISIBLE);
				} else {
					holder.imageView.setVisibility(View.INVISIBLE);
				}
				holder.titleView.setText(alarms.get(position).getTitle());
			} catch (Exception e) {
				e.printStackTrace();
			}
			return convertView;
		}

		class ViewHolder {
			View mainContainer;
			ImageView imageView;
			TextView titleView;
		}

		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		public int getCount() {
			return alarms.size();
		}

		public Object getItem(int position) {
			return alarms.get(position);
		}
	}

	// ////////////////////////////
	private long diff;
	private TimerTask timerTask;
	private Timer timer;

	private void startTimer() {
		try {
			if (timer != null) {
				timer.cancel();
			}
			if (timerTask != null) {
				timerTask.cancel();
			}
			timer = new Timer();
			timerTask = new UITimerTask();
			messageContainer.setVisibility(View.VISIBLE);
			timer.schedule(timerTask, 0, 500);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private class UITimerTask extends TimerTask {
		@Override
		public void run() {
			try {
				mHandler.post(new Runnable() {

					public void run() {
						mHandler.post(new Runnable() {

							public void run() {
								diff = alarmTime - System.currentTimeMillis();
								if ((!isFinishing()) && (diff > 0)) {
									long sec = diff / 1000;
									long min = sec / 60;
									long hour = min / 60;
									String timeSting = String.format(
											"Playing \"%s\" in %d:%02d:%02d",
											selectedAlarmTitle, hour, min % 60,
											sec % 60);
									messageView.setText(timeSting);
								} else {
									timer.cancel();
									timerTask.cancel();
									timer = null;
									timerTask = null;
									if (!isFinishing()) {
										messageContainer
												.setVisibility(View.GONE);
									}
								}

							}
						});

					}
				});
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}